<template>
  <div class="alarm-management p-4">
    <!-- 告警列表 -->
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3>告警声音管理</h3>
          <el-button type="primary" @click="handleAdd" v-if="alarmko">添加告警</el-button>
        </div>
      </template>

      <el-table :data="alarmList" border>
        <el-table-column prop="name" label="告警名称" />
        <el-table-column prop="audioFile" label="音频文件">
          <template #default="{ row }">
            {{ row.useDefaultSound ? '默认提示音' : row.audioFile }}
          </template>
        </el-table-column>
        <el-table-column prop="playTimes" label="播放次数" />
        <el-table-column prop="playInterval" label="播放间隔(秒)" />
        <el-table-column prop="useDefaultSound" label="使用默认声音" width="140">
          <template #default="{ row }">
            <el-tag :type="row.useDefaultSound ? 'success' : 'info'">
              {{ row.useDefaultSound ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="380">
          <template #default="{ row }">
            <div class="flex items-center">
              <el-button type="success" link @click="handleTest(row)">
                测试
                <audio :ref="el => setAudioRef(row.id, el)" :src="getAudioSource(row)" preload="auto"
                  @ended="handleAudioEnded"></audio>
              </el-button>
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <!-- 播放状态显示 -->
              <div v-if="playbackState.audio === audioRefs[row.id] && playbackState.isActive" class="ml-4 text-sm">
                <div class="text-gray-600">
                  已播放: {{ playbackState.currentCount }}/{{ playbackState.totalTimes }}次
                </div>
                <div v-if="playbackState.currentCount < playbackState.totalTimes" class="text-gray-600">
                  下次播放倒计时: {{ countdown }}秒
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="告警名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入告警名称" />
        </el-form-item>

        <el-form-item label="默认声音" prop="useDefaultSound">
          <el-switch v-model="formData.useDefaultSound" :active-value="1" :inactive-value="0" />
          <span class="ml-2 text-gray-500 text-sm">开启后将使用系统默认提示音</span>
        </el-form-item>

        <el-form-item label="自动告警" prop="useDefaultSound">
          <el-switch v-model="formData.display" :active-value="1" :inactive-value="0" />
          <span class="ml-2 text-gray-500 text-sm">开启后将自动播放告警声音</span>
        </el-form-item>

        <el-form-item label="音频文件" prop="audioFile" v-if="!formData.useDefaultSound">
          <el-select v-model="formData.audioFile" placeholder="请选择音频文件">
            <el-option v-for="i in 20" :key="i" :label="`${i}.wav`" :value="`${i}.wav`" />
          </el-select>
          <audio ref="testAudio" :src="getAudioSource(formData)" preload="auto" @ended="handleAudioEnded"></audio>
        </el-form-item>

        <el-form-item label="播放次数" prop="playTimes">
          <el-input-number v-model="formData.playTimes" :min="0" :max="10" controls-position="right" />
          <span class="ml-2 text-gray-500 text-sm">设置为1表示仅播放一次</span>
        </el-form-item>

        <el-form-item label="播放间隔" prop="playInterval">
          <el-input-number v-model="formData.playInterval" :min="1" :max="60" controls-position="right" />
          <span class="ml-2 text-gray-500 text-sm">秒</span>
        </el-form-item>

        <el-form-item label="测试" v-if="formData.useDefaultSound === 0">
          <div class="flex items-center">
            <el-button type="success" @click="handleTestInDialog">
              告警测试
            </el-button>
            <!-- 弹窗中的播放状态显示 -->
            <div v-if="playbackState.audio" class="ml-4 text-sm" style="margin-top: 10px;">
              <div class="text-gray-600">
                已播放: {{ playbackState.currentCount }}/{{ playbackState.totalTimes }}次
              </div>
              <div v-if="playbackState.currentCount < playbackState.totalTimes" class="text-gray-600">
                下次播放倒计时: {{ countdown }}秒
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { getList, addObj, putObj } from '@/api/audio'

// 告警列表数据
const alarmList = ref([])
const formRef = ref(null)
const testAudio = ref(null)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const audioRefs = reactive({})
const alarmko = ref(true)
const countdown = ref(0)

// 播放状态管理
const playbackState = reactive({
  audio: null,
  totalTimes: 0,        // 总播放次数
  currentCount: 1,      // 当前播放次数
  interval: 3,
  timeoutId: null,
  isPlaying: false,
  isActive: false,      // 是否在活动状态（包括播放和等待）
  countdownInterval: null // 倒计时定时器
})

const formData = reactive({
  name: '',
  audioFile: '',
  display: 0,
  playTimes: 0,
  playInterval: 3,
  useDefaultSound: 0
})

// 更新倒计时
const startCountdown = (duration) => {
  // 清理现有倒计时
  if (playbackState.countdownInterval) {
    clearInterval(playbackState.countdownInterval)
  }

  countdown.value = duration

  playbackState.countdownInterval = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(playbackState.countdownInterval)
      playbackState.countdownInterval = null
    }
  }, 1000)
}

// 停止倒计时
const stopCountdown = () => {
  if (playbackState.countdownInterval) {
    clearInterval(playbackState.countdownInterval)
    playbackState.countdownInterval = null
  }
  countdown.value = 0
}

// 设置音频引用
const setAudioRef = (id, el) => {
  if (el) {
    audioRefs[id] = el
  }
}

// 获取音频源
const getAudioSource = (row) => {
  if (row.useDefaultSound) {
    return '/audio/default.wav'
  }
  return `/audio/${row.audioFile}`
}

// 停止当前播放
const stopCurrentPlayback = () => {
  if (playbackState.timeoutId) {
    clearTimeout(playbackState.timeoutId)
    playbackState.timeoutId = null
  }

  if (playbackState.audio) {
    playbackState.audio.pause()
    playbackState.audio.currentTime = 0
    playbackState.audio = null
  }

  playbackState.totalTimes = 0
  playbackState.currentCount = 1
  playbackState.isPlaying = false
  playbackState.isActive = false

  stopCountdown()
}

// 播放下一次
const playNext = () => {
  if (!playbackState.audio || playbackState.currentCount >= playbackState.totalTimes) {
    stopCurrentPlayback()
    return
  }

  playbackState.isPlaying = true
  playbackState.audio.currentTime = 0
  playbackState.audio.play().catch(err => {
    console.error('播放失败:', err)
    ElMessage.error('音频播放失败，请检查音频文件是否存在')
    stopCurrentPlayback()
  })
}

// 处理音频播放结束事件
const handleAudioEnded = () => {
  playbackState.isPlaying = false
  playbackState.currentCount++

  // 如果还没有播放完所有次数，等待间隔时间后播放下一次
  if (playbackState.currentCount < playbackState.totalTimes) {
    startCountdown(playbackState.interval) // 开始倒计时
    playbackState.timeoutId = setTimeout(() => {
      playNext()
    }, playbackState.interval * 1000)
  } else {
    stopCurrentPlayback()
  }
}

// 开始播放音频
const playAudio = async (audio, times = 1, interval = 3) => {
  stopCurrentPlayback()

  if (!audio || times <= 0) return

  playbackState.audio = audio
  playbackState.totalTimes = times
  playbackState.currentCount = 0
  playbackState.interval = interval
  playbackState.isActive = true

  // 开始第一次播放
  playNext()
}

// 测试播放（列表中）
const handleTest = (row) => {
  const audio = audioRefs[row.id]
  if (audio) {
    playAudio(audio, row.playTimes || 1, row.playInterval || 3)
  } else {
    ElMessage.error('音频元素未找到')
  }
}

// 测试播放（弹窗中）
const handleTestInDialog = () => {
  if (testAudio.value) {
    playAudio(testAudio.value, formData.playTimes || 1, formData.playInterval || 3)
  } else {
    ElMessage.error('音频元素未找到')
  }
}

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入告警名称', trigger: 'blur' }],
  audioFile: [{ required: true, message: '请选择音频文件', trigger: 'change' }],
  playTimes: [{ required: true, message: '请输入播放次数', trigger: 'blur' }],
  playInterval: [{ required: true, message: '请输入播放间隔', trigger: 'blur' }]
}

// 获取告警列表
const getAlarmList = async () => {
  try {
    const params = {
      userId: '',
      pageNum: 1,
      pageSize: 10
    }
    const res = await getList(params)
    alarmList.value = res.data.list
    alarmko.value = res.data.list.length ? false : true
  } catch (error) {
    ElMessage.error('获取告警列表失败')
  }
}

// 添加告警
const handleAdd = () => {
  dialogTitle.value = '添加告警'
  dialogVisible.value = true
  Object.assign(formData, {
    name: '',
    audioFile: '',
    playTimes: 0,
    display: 0,
    playInterval: 3,
    useDefaultSound: 0
  })
}

// 编辑告警
const handleEdit = (row) => {
  dialogTitle.value = '编辑告警'
  dialogVisible.value = true
  Object.assign(formData, row)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (formData.id) {
        await putObj(formData)
      } else {
        await addObj(formData)
      }
      ElMessage.success(formData.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      getAlarmList()
    } catch (error) {
      ElMessage.error(formData.id ? '更新失败' : '添加失败')
    }
  })
}

// 组件初始化
onMounted(() => {
  getAlarmList()
})

// 组件销毁前清理
onBeforeUnmount(() => {
  stopCurrentPlayback()
})
</script>

<style lang="less" scoped>
.alarm-management {
  width: calc(100% - 40px);
  padding: 20px;
}
</style>